/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-09-29
*/
package com.rzico.order.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.account.entity.Refunds;
import com.rzico.account.model.Attach;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.entity.Filter;
import com.rzico.entity.Pageable;
import com.rzico.entity.PageResult;
import com.rzico.order.entity.BargainBuy;
import com.rzico.order.entity.BargainProduct;
import com.rzico.order.entity.GroupBuy;
import com.rzico.order.service.*;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.Api;
import com.rzico.util.StringUtils;

import java.util.*;

/**
 * 砍价活动控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-09-29
 */
@Api(description = "砍价活动接口")
@RestController
@RequestMapping("/admin/bargainBuy")
public class BargainBuyAdminController extends BaseController {

    @Autowired
    private BargainBuyService bargainBuyService;
    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private BargainProductService bargainProductService;

    /**
     * 分页查询砍价活动
     *
     * @return
    */
    @ApiOperation("分页查询砍价活动")
    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态（0.待审核，1.进行中, 2.已完成,3.已取消）", dataType = "String", paramType = "query")
    })
    public CommResult<BargainBuy> list(Date startDate, Date endDate,Integer status, Pageable pageable) {
        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);
        if (startDate!=null){
           params.put("startDate", startDate);
        }
        if (endDate!=null){
           params.put("endDate", DateUtils.addMilliseconds(DateUtils.addDays(endDate,1),-1));
        }

        if (status!=null){
            params.put("status", status);
        }

        Enterprise enterprise = enterpriseService.getCurrent();
        if (enterprise!=null) {
            params.put("enterpriseId", enterprise.getId());
        } else {
            return CommResult.error("没有开通企业");
        }

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<BargainBuy> list = bargainBuyService.selectList(params);
        PageResult<BargainBuy> pageResult = new PageResult<BargainBuy>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);
    }

    /**
     * 查询单条砍价活动
     *
     * @return
    */
    @ApiOperation("查询单条砍价活动")
    @GetMapping("/find/{id}")
    public CommResult<BargainBuy> find(@PathVariable String id) {
        BargainBuy result = bargainBuyService.findById(id);
        result.setArticle(result.getMetaAndContent());
        result.setItemList(bargainProductService.getItemList(result.getId()));

        Map<String,Object> data = new HashMap<>();
        data.put("bargainBuy",result);
        return CommResult.success(data);

    }

    /**
     * 保存砍价活动
     *
     * @param bargainBuy
     * @return
     */
    @ApiOperation("保存砍价活动")
    @PostMapping("/save")
    public CommResult<BargainBuy> save(@RequestBody BargainBuy bargainBuy) {
        Enterprise enterprise = enterpriseService.getCurrent();
        bargainBuy.setEnterpriseId(enterprise.getId());
        bargainBuy.setCreateDate(new Date());
        bargainBuy.setDeleted(false);
        if (bargainBuy.getArticle()!=null) {
            bargainBuy.setMeta(JSON.toJSONString(bargainBuy.getArticle().getProductMeta()));
            bargainBuy.setContent(bargainBuy.getArticle().getContent());
        }

        int affectCount = bargainBuyService.save(bargainBuy);
        if (affectCount <= 0) {
            return CommResult.error();
        }
        BargainBuy result = bargainBuyService.findById(bargainBuy.getId());
        return CommResult.success(result);

    }


    /**
     * 批量删除砍价活动
     *
     * @param ids
     * @return
     */
    @Log(desc = "批量删除砍价活动", type = Log.LOG_TYPE.DEL)
    @ApiOperation("批量删除砍价活动,ids用逗号拼接")
    @PostMapping("/del/{ids}")
    public CommResult<BargainBuy> del(@PathVariable String ids) {

        try {
            bargainBuyService.deleteByIds(ids.split(","));
        } catch (Exception e) {
            return CommResult.error(e.getMessage());
        }
        return CommResult.success();
    }

    /**
     * 更新砍价活动
     *
     * @param bargainBuy
     * @return
     */
    @Log(desc = "更新砍价活动", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("更新砍价活动")
    @PostMapping("/update")
    public CommResult<BargainBuy> update(@RequestBody BargainBuy bargainBuy) {

        BargainBuy buy = bargainBuyService.selectByPrimaryKey(bargainBuy.getId());
        if (!buy.getStatus().equals(0)) {
            return CommResult.error("已审核不能修改");
        }

        if (bargainBuy.getArticle()!=null) {
            bargainBuy.setMeta(JSON.toJSONString(bargainBuy.getArticle().getProductMeta()));
            bargainBuy.setContent(bargainBuy.getArticle().getContent());
        }

        int affectCount = bargainBuyService.update(bargainBuy);
        if (affectCount <= 0){
            return CommResult.error();
        }
        BargainBuy result = bargainBuyService.findById(bargainBuy.getId());
        return CommResult.success(result);
    }



    /**
     * 审核团购
     *
     * @param bargainBuy
     * @return
     */
    @Log(desc = "审核团购", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("审核团购")
    @PostMapping("/audit")
    public CommResult<BargainBuy> audit(@RequestBody BargainBuy bargainBuy) {

        bargainBuy = bargainBuyService.selectByPrimaryKey(bargainBuy.getId());
        if (!bargainBuy.getStatus().equals(0)) {
            return CommResult.error("不在待审核");
        }

        bargainBuy.setStatus(1);

        int affectCount = bargainBuyService.audit(bargainBuy);
        if (affectCount <= 0){
            return CommResult.error();
        }
        BargainBuy result = bargainBuyService.findById(bargainBuy.getId());
        return CommResult.success(result);

    }


    /**
     * 弃审团购
     *
     * @param bargainBuy
     * @return
     */
    @Log(desc = "弃审团购", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("弃审团购")
    @PostMapping("/unAudit")
    public CommResult<BargainBuy> unAudit(@RequestBody BargainBuy bargainBuy) {

        bargainBuy = bargainBuyService.selectByPrimaryKey(bargainBuy.getId());
        if (!bargainBuy.getStatus().equals(1)) {
            return CommResult.error("不在已审核");
        }

//        if (bargainBuy.getPeriodNum()>1) {
//            return CommResult.error("已执行不能弃审");
//        }

        int affectCount = bargainBuyService.unAudit(bargainBuy);
        if (affectCount <= 0){
            return CommResult.error();
        }
        BargainBuy result = bargainBuyService.findById(bargainBuy.getId());
        return CommResult.success(result);

    }


    /**
     * 关闭团购
     *
     * @param id
     * @return
     */
    @Log(desc = "关闭团购", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("关闭团购,未完成的全额退款")
    @PostMapping("/cancel")
    public CommResult<BargainBuy> cancel(Long id) {
        BargainBuy bargainBuy = bargainBuyService.selectByPrimaryKey(id);

        List<Refunds> refundsList = bargainBuyService.cancel(bargainBuy);

//        for (Refunds refunds:refundsList) {
//            //TODO发送退款通知
//            Attach attachQueue = new Attach();
//            attachQueue.setCode("0000");
//            attachQueue.setId(String.valueOf(refunds.getId()));
//            attachQueue.setQueue("queue.refunds.submit");
//            Message message = MessageBuilder
//                    .withBody(JSON.toJSONString(attachQueue).getBytes())
//                    .setContentType(MessageProperties.CONTENT_TYPE_JSON)
//                    .build();
//            CorrelationData correlationData = new CorrelationData();
//            correlationData.setId(UUID.randomUUID().toString());
//            logger.info("发送 MQ");
//            rabbitTemplate.convertAndSend("directExchange",attachQueue.getQueue()+".key", message, correlationData);
//
//        }

        BargainBuy result = bargainBuyService.findById(bargainBuy.getId());
        return CommResult.success(result);

    }

}
